package com.yangfei.mystudy1020.View;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.yangfei.mystudy1020.utils.ScreenUtils;

/**
 * 以宽度为基准的自适应Imageview
 * Created by wangw on 2017/11/1.
 */

public class FitImageView extends AppCompatImageView {
    private int mImgW = -1;
    private int mImgH = -1;
    private int mRotate = 0;
    public FitImageView(Context context) {
        super(context);
        onInitView();
    }

    public FitImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        onInitView();
    }

    public FitImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        onInitView();
    }

    public void setSize(int width, int height, int rotate) {
        //如果旋转90度或270度则调换一下图片宽高
//        if (rotate == 90 || rotate == 270) {
//            mImgW = height;
//            mImgH = width;
//        }else {
        mImgW = width;
        mImgH = height;
//        }
        mRotate = rotate;
        requestLayout();
    }

    private void onInitView() {
        setScaleType(ScaleType.CENTER_CROP);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mImgH <= 0 || mImgW <= 0) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }

        int width = getDefaultSize(mImgW, widthMeasureSpec);
        Log.e("FitImageView","onMeasure"+" widthMeasureSpec="+widthMeasureSpec+" heightMeasureSpec="+heightMeasureSpec);
        setMeasuredDimension(width, ScreenUtils.scaleHeight(width,mImgW,mImgH));
        //在服务器数据出现错误宽高的时候，这里会引起oom，原因暂时还不清楚，和colin商量后先做屏蔽处理
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }
}
